<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;


class HotQuestionController extends Controller {

    public $data = array();

    public $need_redirect = 0;

    public $goAuth = false;
    public $goReload = false;

    public function __construct(){
        session_start();
        $this->data['user_agent'] = $this->getUserAgent();



        // if( Input::has('token') && false ){
		// 	$current_uri     = $_SERVER['REQUEST_URI'];
		// 	$token           = Input::get('token');
		// 	$is_dev          = Config::get('lib.is_dev');
		// 	$server_url      = $is_dev ? "http://192.168.2.103:88/user/token/".$token : "http://timepicker.cn/api/user?token=".$token;
        //
		// 	$result = $this->curl_get( $server_url , $token , 'user' );
        //
		// 	if( !$result || $result == "" ){
		// 		$this->data['check_false'] = 1;
		// 	}
		// 	$user_info_array = json_decode($result , true);
        //
		// 	if( isset( $user_info_array['error'] ) && !$user_info_array['error'] ){
		// 		$user_id 	= $user_info_array['result']['id'];
		// 		$number 	= $user_info_array['result']['school_id'] == null ? "" : $user_info_array['result']['school_id'];
		// 		$icon 		= $user_info_array['result']['icon'];
		// 		$name 		= $user_info_array['result']['name'];
        //
        //         $this->data['user_id'] 	= $user_id;
		// 		$this->data['number'] 	= $number;
		// 		$this->data['icon'] 	= $icon;
		// 		$this->data['token'] 	= $token;
		// 		$this->data['name']		= $name;
        //
		// 		Session::put('token' 	, $token);
		// 		Session::put('user_id' 	, $user_id);
		// 		Session::put('number' 	, $number);
		// 		Session::put('icon' 	, $icon);
		// 		Session::put('token' 	, $token);
		// 		Session::put('name'		, $name);
        //
        //         $_SESSION['token']      = $token;
        //         $_SESSION['user_id']    = $user_id;
        //         $_SESSION['number']     = $number;
        //         $_SESSION['icon']       = $icon;
        //         $_SESSION['token']      = $token;
        //         $_SESSION['name']       = $name;
        //         $_SESSION['answer']     = $number > 0 ? 1 : 0;
        //
        //
		// 		$check_user = DB::table('user')->select('id','can_answer')->where('id','=',$user_id)->get();
		// 		//本系统新用户，添加
		// 		if( count($check_user) == 0 ){
		// 			$insert_arr = array(
		// 				'id' => $user_id ,
		// 				'name' => $name ,
		// 				'number' => $number,
        //                 'icon' => $icon,
        //                 'add_time' => date('Y-m-d H:i:s' , time())
		// 			    );
		// 			$insert_id = DB::table('user')->insertGetId($insert_arr);
		// 			if( $insert_id < 1 ){
		// 				$this->data['check_false'] = 1;
		// 			}
		// 		}else{
        //             $update_arr = array(
        //                 'id' => $user_id ,
        //                 'name' => $name ,
        //                 'number' => $number,
        //                 'icon' => $icon,
        //                 );
        //             $_SESSION['answer'] = $check_user[0]->can_answer;
        //             DB::table('user')->where('id','=',$user_id)->update($update_arr);
        //         }
        //
		// 		$current_uri_arr = explode('?' , $current_uri);
		// 		$current_uri = $current_uri_arr[0];
		// 		$opt_uri = "";
		// 		$opt_uri_arr = array();
		// 		$input_arr = Input::all();
		// 		foreach( $input_arr as $key1 => $val1 ){
		// 			if( $key1 != 'token' ){
		// 				$opt_uri_arr[$key1] = $val1;
		// 				if( $opt_uri != "" ){
		// 					$opt_uri .= '&'.$key1.'='.$val1;
		// 				}else{
		// 					$opt_uri .= $key1.'='.$val1;
		// 				}
		// 			}
		// 		}
		// 		if( $opt_uri != "" ){
		// 			$temp = mt_rand(0,100000000);
		// 			$current_uri .= '?'.$opt_uri."&view=".$temp;
		// 		}
		// 		//return Redirect::to($current_uri);
		// 	}else{
        //         $url = Config::get('lib.auth_uri')."?client_id=".Config::get('lib.client_id')."&redirect_uri=".Config::get('lib.return_uri')."&response_type=token&state=1";
        //         header("Location: $url");
        //         exit;
		// 	}
		// 	$this->need_redirect = 1;
		// }else{
            // if( isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0 ){
			// 	$this->data['user_id'] 	= $_SESSION['user_id'];
			// 	$this->data['icon'] 	= $_SESSION['icon'];
			// 	$this->data['number']   = $_SESSION['number'];
			// }else{
            //     $url = Config::get('lib.auth_uri')."?client_id=".Config::get('lib.client_id')."&redirect_uri=".Config::get('lib.return_uri')."&response_type=token&state=1";
            //     header("Location: $url");
            //     exit;
			// }
		// }
    }




    //最新问题
    function hotQuestions(){
        if( Input::has('code') ){
            $code = Input::get('code');
            $arr = array(
                    'client_id' => Config::get('lib.client_id') ,
                    'client_secret' => Config::get('lib.client_secret') ,
                    'code' => $code , 'grant_type' => 'authorization_code'
                );
            $access = $this->curl_post( Config::get('lib.oauth_uri').'/token' , $arr );
            $access_result = json_decode($access , true);
            if( !$access_result['error'] ){
                $user_id        = $access_result['result']['user_id'];
                $token_type     = $access_result['result']['token_type'];
                $access_token   = $access_result['result']['access_token'];

                $_SESSION['user_id']        = $user_id;
                $_SESSION['authorization']  = $token_type.' '.$access_token;

                $info = $this->curl_get( Config::get('lib.ptime_api')."/user/".$user_id , "" , "user" , $token_type.' '.$access_token );
                $info_result = json_decode($info , true);
                if( !$info_result['error'] ){
                    $_SESSION['number'] = $info_result['result']['school_id'];
                    $_SESSION['token']  = $info_result['result']['token'];
                    $_SESSION['name']   = $info_result['result']['name'];
                    $_SESSION['icon']   = $info_result['result']['icon'];

                    $check_user = DB::table('user')->select('id','can_answer')->where('id','=',$user_id)->get();
    				//本系统新用户，添加
    				if( count($check_user) == 0 ){
    					$insert_arr = array(
    						'id' => $user_id ,
    						'name' => $info_result['result']['name'] ,
    						'number' => $info_result['result']['school_id'] ,
                            'icon' => $info_result['result']['icon'] ,
                            'add_time' => date('Y-m-d H:i:s' , time())
    					    );
    					$insert_id = DB::table('user')->insertGetId($insert_arr);
    					if( $insert_id < 1 ){
    						$this->data['check_false'] = 1;
    					}
    				}else{
                        $update_arr = array(
                            'id' => $user_id ,
                            'name' => $info_result['result']['name'] ,
                            'number' => $info_result['result']['school_id'],
                            'icon' => $info_result['result']['icon'] ,
                            );
                        $_SESSION['answer'] = $check_user[0]->can_answer;
                        DB::table('user')->where('id','=',$user_id)->update($update_arr);
                    }
                    if( Input::has('state') ){
                        $redirectUrl = Input::get('state');
                        return redirect($redirectUrl);
                    }
                }
            }
        }

        if( empty($_SESSION['user_id']) ){
            $state          = urlencode("http://".env("APP_URL")."/");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }


        $user_id = $_SESSION['user_id'];
        $result = DB::select("  select
                                question.id , question.title , question.description , question.cover , topic.name , user.icon , count(question_id) as temp_count
                                from
                                user_question
                                join
                                question
                                on
                                question.id = user_question.question_id
                                join
                                topic
                                on
                                topic.id = question.topic_id
                                join
                                user
                                on
                                user.id = question.creator_id
                                where
                                question.is_deleted = 0
                                group by user_question.question_id
                                order by temp_count DESC
                                ");

        $question_attention_arr = array();
        $question_id_arr = array();
        foreach( $result as $key => $val ){
            $question_id_arr[] = $val->id;
        }
        if( count($question_id_arr) > 0 ){
            $str = implode(',' , $question_id_arr);
            $user_attention = DB::table('user_question')->whereIn('question_id' , $question_id_arr)->where('user_id','=',$user_id)->where('is_deleted','=',0)->get();
            foreach( $user_attention as $key => $val ){
                $question_attention_arr[$val->question_id] = 1;
            }
        }

        $this->data['attention_check'] = $question_attention_arr;
        $this->data['hot_results'] = $result;

        $this->data['title']        = "拾光问答";
        $this->data['description']  = "热门问题";

        return view('main' , $this->data);
    }


    function __destruct(){

    }

}
